package www.sharetime.weshare.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import www.sharetime.weshare.R;
import www.sharetime.weshare.adapter.BrandAdapter;
import www.sharetime.weshare.api.ShareTimeAPI;
import www.sharetime.weshare.base.BaseActivity;
import www.sharetime.weshare.event.BrandEvent;
import www.sharetime.weshare.event.GoodsEvent;
import www.sharetime.weshare.interfaces.ClickListener;
import www.sharetime.weshare.interfaces.RecyclerTouchListener;
import www.sharetime.weshare.response.BrandSearchResponse;
import www.sharetime.weshare.response.GoodsSearchResponse;
import www.sharetime.weshare.utils.Constants;
import www.sharetime.weshare.utils.JsonUtils;
import www.sharetime.weshare.utils.L;
import www.sharetime.weshare.utils.NetUtil;
import www.sharetime.weshare.utils.ToastUtils;
import www.sharetime.weshare.utils.UIUtils;
import www.sharetime.weshare.utils.ViewShakeUtil;
import www.sharetime.weshare.view.TipInfoLayout;

import static www.sharetime.weshare.R.id.tv_brand_add;

/**
 * File Description  : 搜索品牌列表
 *
 * @author : zhanggeng
 * @version : v1.0
 *          **************修订历史*************
 * @email : zhanggengdyx@gmail.com
 * @date : 2017/9/21 19:12
 */

public class BrandListActivity extends BaseActivity {


    @BindView(R.id.tv_tag_search_cancle)
    TextView tvTagSearchCancle;
    @BindView(R.id.img_del_search_content)
    ImageView imgDelSearchContent;
    @BindView(tv_brand_add)
    TextView tvBrandAdd;
    @BindView(R.id.edt_search_content)
    EditText edtSearchContent;
    @BindView(R.id.recycler_city)
    RecyclerView recyclerCity;
    @BindView(R.id.tip_info)
    TipInfoLayout tipInfo;
    @BindView(R.id.rl_add_brand)
    RelativeLayout rlAddBrand;
    @BindView(R.id.tv_add_name)
    TextView tvAddName;


    BrandAdapter brandAdapter;

    ArrayList<String> branList = new ArrayList<>();

    BrandSearchResponse brandSearchResponse;

    GoodsSearchResponse goodsSearchResponse;

    int brandEntityId;
    String brandEntityName;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_brand_list;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        brandEntityId = getIntent().getIntExtra("id", -1000);
        brandEntityName = getIntent().getStringExtra("name");

        L.et("idAndName", brandEntityId + "=======" + brandEntityName);

        if (brandEntityId != -1000 && brandEntityName != null) {

            //TODO: 显示标题中的商标名，并请求某品牌下的商品列表
            tvBrandAdd.setVisibility(View.VISIBLE);
            tvBrandAdd.setText(brandEntityName);

            requestByBrandID(brandEntityId);
        }

        recyclerCity.setLayoutManager(new LinearLayoutManager(this));

        onRecyclerItemClick();

        tipInfo.setHiden();

        edtSearchContent.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                onSearchKeyDown(keyCode, event);
                return false;
            }
        });
        //TODO: 当edittext 中内容发生变化的时候，进行处理
        edtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edtSearchContent.getText().toString().equals("")) {
                    updateAdapter(branList);
                }
            }
        });
    }

    private void requestByBrandID(int brandEntityId) {

        if (!NetUtil.isNetworkAvailable(BrandListActivity.this)) {
            //TODO: 当网络状态发生变化时，做出相应动作，可以通过网络状态变化广播来实现
            tipInfo.setLoadError(Constants.NETWORK_CANNOT_USE);
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new FormBody.Builder().build();

        Request request = new Request.Builder()
                .addHeader("Authorization", "5_9f6cad7e465b4cf8803d41a3fcd8c77d")
                .url(ShareTimeAPI.BASE_URL + ShareTimeAPI.searchGoods + "?brandId=" + brandEntityId)
                .post(requestBody)
                .build();


        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                onRequestFailure();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {

                    goodsSearchResponse = JsonUtils.toBean(response.body().string(), new TypeToken<GoodsSearchResponse>() {
                    }.getType());

                    for (int i = 0; i < goodsSearchResponse.getData().size(); i++) {

                        GoodsSearchResponse.GoodsEntity goodsEntity = goodsSearchResponse.getData().get(i);
                        branList.add(goodsEntity.getBrandName() + " " + goodsEntity.getGoodsName());
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateAdapter(branList);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    onRequestFailure();

                }
            }
        });

    }

    private void onRequestFailure() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tipInfo.setEmptyData(Constants.LOADERROR);
                recyclerCity.setVisibility(View.GONE);
            }
        });
    }


    private void onRecyclerItemClick() {
        RecyclerTouchListener recyclerTouchListener = new RecyclerTouchListener(BrandListActivity.this, recyclerCity, new ClickListener() {
            @Override
            public void onClick(View view, int position) {

                if (brandSearchResponse != null) {

                    BrandEvent brandEvent = null;

                    for (int index = 0; index < brandAdapter.getBrandList().size(); index++) {
                        if (brandAdapter.getBrandList().get(position).equals(brandSearchResponse.getData().get(position).getBrandName())) {
                            brandEvent = new BrandEvent(brandSearchResponse.getData().get(position));
                        }
                    }
                    EventBus.getDefault().post(brandEvent);
                }

                if (goodsSearchResponse != null) {
                    //TODO: 商品选择条目后
                    L.et("goods" , brandAdapter.getBrandList().get(position));
                    EventBus.getDefault().post(new GoodsEvent(brandAdapter.getBrandList().get(position)));
                }

                UIUtils.closeActivity(BrandListActivity.this);
            }

            @Override
            public void onLongClick(View view, final int position) {
            }
        });
        recyclerCity.addOnItemTouchListener(recyclerTouchListener);
    }

    private void onSearchKeyDown(int keyCode, KeyEvent event) {
        //是否是回车键
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            //隐藏键盘
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(BrandListActivity.this.getCurrentFocus()
                            .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            if (brandEntityId == -1000) {

                if (!edtSearchContent.getText().toString().trim().equals("")) {
                    //TODO: 发送网络请求
                    rlAddBrand.setVisibility(View.VISIBLE);
                    tvAddName.setText("点击添加: " + edtSearchContent.getText().toString());
                    edtSearchContent.setHint("请输入品牌");
                    requestDataFromNet();
                } else {
                    ViewShakeUtil.shakeViewWithToast(BrandListActivity.this, edtSearchContent, "请输入要搜索的品牌");
                }
            }

            if (goodsSearchResponse != null) {
                if (!edtSearchContent.getText().toString().trim().equals("")) {
                    rlAddBrand.setVisibility(View.VISIBLE);
                    tvAddName.setText("点击添加: " + edtSearchContent.getText().toString());
                } else {
                    ViewShakeUtil.shakeViewWithToast(BrandListActivity.this, edtSearchContent, "请输入要搜索的商品");
                }
            }
        }
    }

    private void updateAdapter(ArrayList<String> contentList) {
        recyclerCity.setVisibility(View.VISIBLE);
        if (brandAdapter != null) {
            brandAdapter.notifyDataChange(contentList);
        } else {
            brandAdapter = new BrandAdapter(contentList, BrandListActivity.this);
            recyclerCity.setAdapter(brandAdapter);
        }

        tipInfo.setVisibility(View.GONE);
    }

    @Override
    public void initData() {
        super.initData();
    }

    private void requestDataFromNet() {

        if (!NetUtil.isNetworkAvailable(BrandListActivity.this)) {
            //TODO: 当网络状态发生变化时，做出相应动作，可以通过网络状态变化广播来实现
            tipInfo.setLoadError(Constants.NETWORK_CANNOT_USE);
            return;
        }

        String brandSearchName = edtSearchContent.getText().toString().trim();

        if (brandSearchName.equals("")) {
            ViewShakeUtil.shakeViewWithToast(BrandListActivity.this, edtSearchContent, "请输入要搜索的品牌");
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new FormBody.Builder().build();

        Request request = new Request.Builder()
                .addHeader("Authorization", "5_9f6cad7e465b4cf8803d41a3fcd8c77d")
                .url(ShareTimeAPI.BASE_URL + ShareTimeAPI.searchBrand + "?brandName=" + brandSearchName)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                onRequestFailure();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    brandSearchResponse = JsonUtils.toBean(
                            response.body().string(),
                            new TypeToken<BrandSearchResponse>() {
                            }.getType());

                    for (int i = 0; i < brandSearchResponse.getData().size(); i++) {
                        branList.add(brandSearchResponse.getData().get(i).getBrandName());
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateAdapter(branList);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    onRequestFailure();

                }
            }
        });
    }

    @OnClick({R.id.tv_tag_search_cancle, R.id.img_del_search_content, R.id.tip_info, R.id.rl_add_brand})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tag_search_cancle:
                UIUtils.closeActivity(this);
                break;
            case R.id.img_del_search_content:
                edtSearchContent.setText("");
                edtSearchContent.setHint("请输入品种");
                break;
            case R.id.tip_info:
                break;
            case R.id.rl_add_brand:
                if (brandSearchResponse != null) {
                    tvBrandAdd.setVisibility(View.VISIBLE);
                    tvBrandAdd.setText(edtSearchContent.getText().toString());
                } else if (goodsSearchResponse != null) {
                    //TODO: 点击后跳转到AddTagList页面
                    L.et("edt", edtSearchContent.getText().toString());
                    EventBus.getDefault().post(new GoodsEvent(edtSearchContent.getText().toString()));
                    UIUtils.closeActivity(this);
                }

                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        UIUtils.closeActivity(this);
        return super.onKeyDown(keyCode, event);
    }

    private void showToast(String remindMessage) {
        ToastUtils.showToastLong(BrandListActivity.this, remindMessage);
    }

}
